package city.spring.modules.consumptionItem.controller;

import city.spring.modules.consumptionItem.entity.ConsumptionItemsEntity;
import city.spring.modules.consumptionItem.service.ConsumptionItemsService;
import city.spring.modules.consumptionItem.vo.ConsumptionItemsEntityVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：收费项目
 *
 * @author pxm
 * @date 2020-08-05 16:18:33
 */
@RestController
@RequestMapping("/consumption_items")
public class ConsumptionItemsController extends ApiController {
    private final ConsumptionItemsService consumptionItemsService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<ConsumptionItemsEntity, ?>> entityOrderFields;

    public ConsumptionItemsController(ConsumptionItemsService consumptionItemsService) {
        this.consumptionItemsService = consumptionItemsService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(ConsumptionItemsEntity::getId);
        entityOrderFields.add(ConsumptionItemsEntity::getName);
        entityOrderFields.add(ConsumptionItemsEntity::getCategoryId);
        entityOrderFields.add(ConsumptionItemsEntity::getChargeWay);
        entityOrderFields.add(ConsumptionItemsEntity::getEffectiveDate);
        entityOrderFields.add(ConsumptionItemsEntity::getCost);
        entityOrderFields.add(ConsumptionItemsEntity::getIsRoom);
        entityOrderFields.add(ConsumptionItemsEntity::getType);
        entityOrderFields.add(ConsumptionItemsEntity::getExecutionDate);
        entityOrderFields.add(ConsumptionItemsEntity::getExecutionTime);
        entityOrderFields.add(ConsumptionItemsEntity::getFrequency);
        entityOrderFields.add(ConsumptionItemsEntity::getGmtCreate);
        entityOrderFields.add(ConsumptionItemsEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>收费项目</strong> 列表
     */
    @GetMapping("{categoryId}/all")
    public Object listAll(@PageableDefault Pageable pageable, ConsumptionItemsEntity entity) {
        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>收费项目</strong> 列表
     *
     * @param pageable 分页参数信息
     */

    @GetMapping("{categoryId}")
    public Object list(@PageableDefault Pageable pageable, ConsumptionItemsEntityVO entity, @PathVariable String categoryId) {
        QueryWrapper<? extends ConsumptionItemsEntity> queryWrapper = buildQuery(entity);
        queryWrapper.eq("t1.category_id", categoryId);
        return success(consumptionItemsService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }
//    @GetMapping("{categoryId}")
//    public Object list(@PageableDefault Pageable pageable, ConsumptionItemsEntity entity, @PathVariable String categoryId) {
//        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        lambdaQuery.eq(ConsumptionItemsEntity::getCategoryId, categoryId);
//        Page<ConsumptionItemsEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取类别为 增值收费 的 收费项目列表
     */
    @GetMapping("getServiceItemList")
    public Object getServiceItemList(@PageableDefault Pageable pageable, ConsumptionItemsEntityVO entity) {
        QueryWrapper<? extends ConsumptionItemsEntity> queryWrapper = buildQuery(entity);
        queryWrapper.eq("t2.pid", "1295979068830904322");
        return success(consumptionItemsService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取全部的 <strong>多级分类信息</strong> 列表
     */
    @GetMapping("tree")
    public Object listTree(@PageableDefault(sort = {"sorted"}) Pageable pageable, ConsumptionItemsEntity entity) {
        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        List<ConsumptionItemsEntity> list = lambdaQuery.list();
        return success(consumptionItemsService.converterToTreeDatasource(list));
    }

    /**
     * 以 父级ID 获取全部的 <strong>菜单信息</strong> 列表
     */
    @GetMapping("list-pid-{categoryId}")
    public Object listPid(@PathVariable(required = false) String categoryId, @PageableDefault(sort = {"sorted"}) Pageable pageable, ConsumptionItemsEntity entity) {
        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        // 搜索条件是否为空
        boolean emptyOfWhere = lambdaQuery.getWrapper().isEmptyOfWhere();
        if (StringUtils.isNotBlank(categoryId)) {

            lambdaQuery.eq(emptyOfWhere, ConsumptionItemsEntity::getCategoryId, categoryId);
        } else {
            // pid 为 null 或者 空字符串
            lambdaQuery.eq(emptyOfWhere, ConsumptionItemsEntity::getCategoryId, "")
                    .or()
                    .isNull(ConsumptionItemsEntity::getCategoryId);
        }
        List<ConsumptionItemsEntity> list = lambdaQuery.list();

        // 这里处理树形结构数据的时候，不自动加载父级信息，因为会与前端已有的数据冲突
        return success(consumptionItemsService.converterToTreeDatasource(list, false));
    }

    /**
     * 获取可以使用的项目列表（前端选择时使用的列表）
     *
     * @param pageable 分页信息
     */
    @GetMapping("selectList")
    public Object list(@PageableDefault Pageable pageable, ConsumptionItemsEntity entity) {
        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<ConsumptionItemsEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }
//    public Object selectUserList(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, ConsumptionItemsEntity entity) {
//        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = buildLambdaQuery(entity);
//        lambdaQuery.select(ConsumptionItemsEntity::getId, ConsumptionItemsEntity::getName, ConsumptionItemsEntity::getCost, ConsumptionItemsEntity::getCategoryId);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<ConsumptionItemsEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }


    /**
     * 获取一个 <strong>收费项目</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{categoryId}/{id}")
    public Object info(@PathVariable String id) {
        return success(consumptionItemsService.getById(id));
    }

    /**
     * 添加一个 <strong>收费项目</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping("{categoryId}")
    public Object add(@RequestBody ConsumptionItemsEntity entity, @PathVariable String categoryId) {
        entity.setCategoryId(categoryId);
        consumptionItemsService.saveConsumptionItems(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(success(entity), headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>收费项目</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{categoryId}/{id}")
    public Object update(@PathVariable String id, @RequestBody ConsumptionItemsEntity entity, @PathVariable String categoryId) {
        entity.setId(id);
        consumptionItemsService.updateConsumptionItems(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>收费项目</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{categoryId}/{id}")
    public Object delete(@PathVariable String id) {
        consumptionItemsService.deleteConsumptionItems(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>收费项目</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping("{categoryId}")
    public Object deleteIds(@RequestBody List<String> ids) {
        consumptionItemsService.deleteConsumptionItems(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<ConsumptionItemsEntity> buildLambdaQuery(ConsumptionItemsEntity entity) {
        LambdaQueryChainWrapper<ConsumptionItemsEntity> lambdaQuery = consumptionItemsService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), ConsumptionItemsEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getName()), ConsumptionItemsEntity::getName, entity.getName());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCategoryId()), ConsumptionItemsEntity::getCategoryId, entity.getCategoryId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getChargeWay()), ConsumptionItemsEntity::getChargeWay, entity.getChargeWay());
        lambdaQuery.eq(entity.getCost() != null, ConsumptionItemsEntity::getCost, entity.getCost());
        lambdaQuery.eq(entity.getTimeNeed() != null, ConsumptionItemsEntity::getTimeNeed, entity.getTimeNeed());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDescribes()), ConsumptionItemsEntity::getDescribes, entity.getDescribes());
        lambdaQuery.eq(entity.getGmtCreate() != null, ConsumptionItemsEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, ConsumptionItemsEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<? extends ConsumptionItemsEntity> buildQuery(ConsumptionItemsEntityVO entity) {
        QueryWrapper<? extends ConsumptionItemsEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.eq(StringUtils.isNotBlank(entity.getPid()), "t2.pid", entity.getPid());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.eq(StringUtils.isNotBlank(entity.getCategoryId()), "t1.category_id", entity.getCategoryId());
        wrapper.eq(StringUtils.isNotBlank(entity.getCategoryName()), "t2.title", entity.getCategoryName());
        wrapper.like(StringUtils.isNotBlank(entity.getChargeWay()), "t1.charge_way", entity.getChargeWay());
        wrapper.eq(entity.getCost() != null, "t1.cost", entity.getCost());
        wrapper.eq(entity.getTimeNeed() != null, "t1.time_need", entity.getTimeNeed());
        wrapper.like(StringUtils.isNotBlank(entity.getDescribes()), "t1.describes", entity.getDescribes());
        wrapper.eq(entity.getGmtCreate() != null, "t1.gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "t1.gmt_modified", entity.getGmtModified());
        return wrapper;
    }

    /**
     * 查找类别是护理并且不是房间的收费项目,list展示
     */
    @GetMapping("/getCategoryListByPidAndIsroom")
    public Object getCategoryListByPidAndIsroom(String categoryId) {
        return success(consumptionItemsService.getCategoryListByPidAndIsroom(categoryId));
    }

    /**
     * 根据护理级别id，床位id 查找护理级别下的床位消费项目的信息 获取床位费用
     *
     * @param categoryId
     * @param bedId
     * @return
     */
    @GetMapping("/getBedFee")
    public Object getBedFee(String categoryId, String bedId) {
        return success(consumptionItemsService.getBedFee(categoryId, bedId));
    }
}
